package indi.mozping.kafka.pc;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Properties;

/**
 * @author by mozping
 * @Classname MyConsumer
 * @Description TODO
 * @Date 2019/7/20 16:49
 */
public class MyKafkaConsumer {

    public static final String BROKER_LIST = "192.168.13.53:9092";
    public static final String TOPIC = "testTopic-2";
    public static final String GROUP_ID = "consumer-mzp-1";
    public static final String CLIENT_ID = "consumer-1";


    public static Properties initConfig() {
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
        properties.put(ConsumerConfig.CLIENT_ID_CONFIG, CLIENT_ID);
        return properties;
    }

    public static void main(String[] args) {
        consumer();
    }

    private static void consumer() {
        Properties prop = initConfig();
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(prop);
        consumer.subscribe(Arrays.asList(TOPIC));

        try {
            while (true) {
                ConsumerRecords<String, String> poll = consumer.poll(1000);
                for (ConsumerRecord<String, String> record : poll) {
                    System.out.println("Record：" + record.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            consumer.close();
        }
    }
}
